package com.extension.company.common.mvp;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;

import butterknife.ButterKnife;
import butterknife.Unbinder;

public abstract class BaseFragment<V extends IView, P extends BasePresenter> extends Fragment {
	protected P presenter;
	protected View contentView;
	private Unbinder unbinder;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		//初始化视图和数据
		contentView = getActivity().getLayoutInflater().inflate(getMainLayout(), null);
		//创建Presenter
		presenter = createPresenter();
		if (presenter != null) {
			//将View层注册到Presenter中
			presenter.registerView(createView());
			//将Mode层注册到presenter
			presenter.registerModel();
		}

		unbinder = ButterKnife.bind(this, contentView);
		init();

	}

	public abstract V createView();

	public abstract P createPresenter();

	@Override
	public View onCreateView(LayoutInflater inflater,
							 ViewGroup container, Bundle savedInstanceState) {
		return contentView;//这里是返回的视图
	}

	/**
	 * 注册组件
	 *
	 * @param id
	 * @param <T>
	 * @return
	 */
	protected <T extends View> T getViewById(int id) {
		return (T) contentView.findViewById(id);
	}

	/**
	 * 注册组件，基于View
	 *
	 * @param view
	 * @param id
	 * @param <T>
	 * @return
	 */
	protected <T extends View> T getViewById(View view, int id) {
		return (T) view.findViewById(id);
	}

	/**
	 * 获得主界面layout资源
	 *
	 * @return
	 */
	public abstract void init();

	/**
	 * 获得主界面layout资源
	 *
	 * @return
	 */
	public abstract int getMainLayout();

	@Override
	public void onDestroyView() {
		super.onDestroyView();
		if (unbinder != null) {
			unbinder.unbind();
		}
		if (presenter != null) {
			//Fragment销毁时的调用，让具体实现BasePresenter中onViewDestroy()方法做出决定
			presenter.destroy();
		}
		//在销毁视图的时候，把父控件remove一下，不然重新加载的时候会异常导致奔溃，提示should remove parent view
		ViewGroup mGroup = (ViewGroup) contentView.getParent();
		if (mGroup != null) {
			mGroup.removeAllViewsInLayout();
		}
	}
}
